package com.witer.serial;


import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

import android_serialport_api.SerialPort;


public class MyserialActivity extends Activity {
    private static final String TAG = "MyserialActivity";

    EditText mReception;
    FileOutputStream mOutputStream;
    FileInputStream mInputStream;
    SerialPort sp;
    ReadThread mReadThread;

    //添加设备
    byte[] startAddEntity = {(byte) 0xaa, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x07, 0x66,
            (byte) 0xba, 0x00, 0x00, 0x00, 0x07, 0x56, 0x01, (byte) 0xa5};

    @Override

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

//	发送  	0xaa,0x00,0x00,0x00,0x03,0x00,0x00,0x07,0x66,0xba,0x00,0x00,0x00,0x07,0x56,0x01,0xa5
        //接收 0xaa,0x00,0x00,0x00,0x1c,0x00,0x00,0x07,0x6c,0x51,0x00,0x00,0x00,0x07,0x56,0x01,0x68,
        final Button buttonSetup = (Button) findViewById(R.id.ButtonSent);
        buttonSetup.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mReception = (EditText) findViewById(R.id.EditTextEmission);

                try {
                    sp = new SerialPort(new File("/dev/ttyS2"), 115200, 0);
                    mInputStream = (FileInputStream) sp.getInputStream();
                    mOutputStream = (FileOutputStream) sp.getOutputStream();
                    Log.d(TAG, "onClick: 端口打开成功");
                    mReadThread = new ReadThread();
                    mReadThread.start();
                } catch (Exception e) {
                    Log.d(TAG, "onClick: 端口打开失败");
                    e.printStackTrace();
                }


                //Toast.makeText(getApplicationContext(), "open",
                // Toast.LENGTH_SHORT).show();

            }
        });


        final Button buttonsend = (Button) findViewById(R.id.ButtonSent1);
        buttonsend.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                try {


                    mOutputStream.write(startAddEntity);
                    mOutputStream.write('\n');
                } catch (IOException e) {
                    e.printStackTrace();
                }


                Toast.makeText(getApplicationContext(), "send",
                        Toast.LENGTH_SHORT).show();

            }
        });


        final Button buttonrec = (Button) findViewById(R.id.ButtonRec);
        buttonrec.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                int size;

                try {
                    byte[] buffer = new byte[64];
                    if (mInputStream == null) return;
                    size = mInputStream.read(buffer);
                    if (size > 0) {
//                        onDataReceived(buffer, size);

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }


            }
        });


    }

    /**
     * 收到数据
     */
    private class ReadThread extends Thread {

        @Override
        public void run() {
            super.run();
            Log.d(TAG, "run: 启动接收线程");
            while (!isInterrupted()) {
                int size;
                try {
                    byte[] buffer = new byte[64];
                    if (mInputStream == null) return;
                    size = mInputStream.read(buffer);
                    if (size > 0) {
                        addReceData(buffer, size);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
            }
        }
    }


    int receLen = 256;
    byte[] receData = new byte[receLen];
    /**
     * 数据池的数据序号
     */
    int index = 0;
    final int HAND_DATA_LEN = 10;

    void addReceData(byte[] data, int size) {
        Log.d(TAG, "run: 接收线程  接收到数据 --》 " + bytesHexString(Arrays.copyOf(data, size)));
        for (int i = 0; i < size; i++) {
            receData[index] = data[i];
            index++;
            /** 超出缓出池从0开始写入 */
            if (index == receData.length) {
                index = 0;
            }
        }
        //串口单词读取到的数据
//        if(serialInputStreamListener != null){
//            serialInputStreamListener.onDataReceived(packData, packData.length);
//        }
        for (int i = 0; i < receData.length; i++) {
            if (receData[i] == (byte) 0xaa) {
                byte[] tempData = new byte[receLen];
                for (int j = 0; j < receData.length - i; j++) {
                    tempData[j] = receData[i + j];
                }
                for (int j = 0; j < i; j++) {
                    tempData[receData.length - i + j] = receData[j];
                }

                int len = (tempData[7] & 0xff) | ((tempData[6] << 8) & 0xff00);
                if (tempData[0] == (byte) 0xaa && len > 0 && len < receLen - HAND_DATA_LEN) {
                    byte[] packData = new byte[HAND_DATA_LEN + len];
                    for (int p = 0; p < packData.length; p++) {
                        packData[p] = tempData[p];
                    }
                    int[] crc_arr = new int[packData.length];
                    for (int c = 0; c < crc_arr.length; c++) {
                        crc_arr[c] = packData[c] & 0xFF;
                    }
                    crc_arr[8] = 0;
                    crc_arr[9] = 0;
                    int[] crc_int = DataPackUtils.Crc16(crc_arr);
                    if (crc_int[0] == (packData[9] & 0xFF) && crc_int[1] == (packData[8] & 0xFF)) {
                        System.out.println("packData > " + index + "," + i + "," + bytesHexString(packData));
                        if (receData.length > i + packData.length) {
                            for (int n = 0; n < packData.length; n++) {
                                receData[i + n] = 0x00;
                            }
                        } else {
                            for (int n = 0; n < receData.length - i; n++) {
                                receData[n + i] = 0x00;
                            }
                            for (int n = 0; n < packData.length - (receData.length - i); n++) {
                                receData[n] = 0x00;
                            }
                        }
                        System.out.println(bytesHexString(receData));
                        //解析后 一条完整的数据
//                        if(serialInputStreamListener != null){
//                            serialInputStreamListener.onDataReceived(packData, packData.length);
//                        }
                    }
                }
            }
        }
    }

    public static String bytesHexString(byte[] b) {
        String ret = "";
        if (b != null) {
            for (int i = 0; i < b.length; i++) {
                String hex = Integer.toHexString(b[i] & 0xFF);
                if (hex.length() == 1) {
                    hex = "0x0" + hex + ",";
                } else {
                    hex = "0x" + hex + ",";
                }
                ret += hex;
            }
        }
        return ret;
    }
}